import { Component, Injector } from "@angular/core";
import { Events } from 'ionic-angular';
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
import { BasePage } from "./../../pages/basePage";
import { StorageService } from "./../../providers/StorageService";
import { UserService } from "./../../providers/UserService";
import { PIC_URL } from "./../../providers/Config";
declare var $: any;
declare var cordova: any;

/**
 * Generated class for the PagemenupageComponent component.
 *
 * See https://angular.io/api/core/Component for more info on Angular
 * Components.
 */
@Component({
  selector: 'pagemenupage',
  templateUrl: 'pagemenupage.html',
})
export class PagemenupageComponent extends BasePage {
  text: string;
  flag: boolean;
  picrooturl = "";//图片服务地址
  userinfo = {}//获取内存中的数据
  orderlist = [];
  orderTmp = [];
  successOK = '';
  value = 123;
  pop = 1;    //分页
  bottom1: boolean = false;    //加载全部底部显示器
  status = 1;

  constructor(injector: Injector, public events: Events, public userService: UserService, public stc: StorageService) {
    super(injector);
    this.picrooturl = PIC_URL;
    this.userinfo = this.stc.read("userinfo");
    this.getMyOrderListAPI('');
    events.subscribe('user:created',(key)=>{
      if(key == 0){
        console.log("全部有数据更新");
        this.again();
      }
    })
  }

  //获取消费者订单
  async getMyOrderListAPI(infiniteScroll) {
    let param = { "user_id": this.userinfo['user_id'], "order_type": 0,pop:this.pop}; 
    let result = await this.userService.getMyOrderListAPI(param);
    console.log(result)
    if (result.code == 1) {
      this.pop++;
      this.orderlist=this.orderlist.concat(result.data);
      if(this.orderlist.length == 0){
        this.flag=false;
      }else{
        this.flag=true;
      }
      if(infiniteScroll){
        this.bottom1=false;
        infiniteScroll.complete(); //请求完成数据更新页面
        if(result.data.length<6){
            $(".contain ion-infinite-scroll-content").css("display","none");
            this.bottom1=true;
        }
      }
     
    }else{
      this.flag =false;
      let toast = this.toastCtrl.create({
        message: result.msg,
        duration: 2000,
        position: 'bottom',
      })
      toast.present();
    }
  }


  /**评论信息填写 */
  comment(item) {
    this.stc.removeItem("back");
    let modal = this.modalCtrl.create("CommentPage", {item:item,par:0});
    modal.onDidDismiss(data => {
      if(data=="ok"){
        let key=0;
        this.events.publish("user:created",key)
      }
    });
    modal.present();
  }

  //无限滚动
  doInfinite(infiniteScroll) {
    this.bottom1 = false;
    this.getMyOrderListAPI(infiniteScroll);
  }
  /**
   *删除订单
   * @param i 删除的某项订单
   */
  async deletOrder(i){
    console.log(i)
    let param = { order_sn: i.order_sn, user_id: this.userinfo['user_id'], operate_type: 3 }
    let result = await this.userService.editOrderAPI(param);
    console.log(result);
    if (result.error_code == 0) {
      let toast = this.toastCtrl.create({
        message: '删除成功！',
        duration: 1500,
        position: 'bottom',
      })
      toast.present();
      let key=0;
      this.events.publish("user:created",key)
    } else {
      let toast = this.toastCtrl.create({
        message: result.msg,
        duration: 1500,
        position: 'bottom',
      })
      toast.present();
    }
  }

  /**调用支付宝，获取支付信息 */
  async editOrderAPI(item) {
    let param = {
      order_sn: item.order_sn,
      operate_type: 4,
      pay_type: 1,
      order_price: item.order_price,
      nail_name: item.nail_name
    };
    let result = await this.userService.editOrderAPI(param);
    if (result.code != 1) {
      let toast = this.toastCtrl.create({
        message: result.msg,
        duration: 3000,
        position: "top"
      });
      toast.present();
      return false;
    }
    console.log(result);
    this.successOK = result.data;
    //let payInfo = this.unescapeHTML(this.successOK);
    cordova.plugins.alipay.payment(
      this.successOK,
      success => {
        //支付成功
        
      },
      error => {
        //支付失败
      }
    );
  }
  /**去支付 */
  gotopay(item) {
    this.actionCtrl
      .create({
        buttons: [
          {
            text: "支付宝支付",
            handler: () => {
              //let alipaystr = this.editOrderAPI(item);

              this.aliPay();
            }
          },
          // {
          //   text: "微信支付",
          //   handler: () => {
          //     this.aliPay2();
          //   }
          // },
          {
            text: "取消",
            role: "cancel"
          }
        ]
      })
      .present();
  }

  unescapeHTML(a) {
    //let aNew = "" + a;
    let str =
      "app_id=2016121504287738&biz_content=%7B%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22laravel%22%2C%22out_trade_no%22%3A%22SN23788%22%2C%22total_amount%22%3A120%2C%22body%22%3A%22%22%22seller_id%22%3A%2218827403620%40139.com%22%7D&charset=UTF-8&format=JSON&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F192.168.1.99%3A1114%2FAdmin%2FAlipay%2Fnotifyurl&sign_type=RSA&timestamp=2018-02-09+09%3A52%3A06&version=1.0&sign=jVC%2FjWMqeVaKTOM4mntqV6hiSUC1Kn5SVHG981up1taiUGCHIQpHAz%2BqEz9%2FSjNRLhoMNEaYJGRf4E5fmkjzM6MBPQkGywFabZ%2Fr%2Bk0t6Iyrq9AKu6i1O0STSzTjjAaS9y%2BaQpq5fSJ190FLVfKAzstYuhVUXkCNw%2B%2FWCff4dt8%3D";
    //return aNew.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'");
    return str;
  }

  aliPay() {
    console.log(333);
    $.post(
      "http://116.62.162.165:1228/api/alipay/uniformPayGateway",
      {
        subject: "美甲款式",
        outTradeNo: "SN2372323",
        totalAmount: 0.01,
        payType: 2
      },
      data => {
        //let payInfo=this.unescapeHTML(data);
        console.log(data);

        cordova.plugins.alipay.payment(data, success => { }, error => { });
      }
    );
  }

  aliPay2() {
    $.post(
      "http://192.168.1.99:1114/api/common/uniformPayer",
      {
        pay_type: 1,
        out_trade_no: "SN23788",
        subject: "laravel",
        total_amount: 0.01,
        alipay_type: 2
      },
      data => {
        //let payInfo=this.unescapeHTML(data);
        console.log(data);
        data = this.unescapeHTML(data);

        console.log(data);

        cordova.plugins.alipay.payment(data, success => { }, error => { });
      }
    );
  }

  /**
   * 点击退款跳转申请退款
   * @param val 当前订单信息
   */
  refund(val) {
    this.stc.removeItem("back");
    let modal = this.modalCtrl.create("ApplicationPage", { "item": val, "par": 0 });
    modal.onDidDismiss(data => {
      console.log(data)
      if(data=="ok"){
       this.again();  
       let key=0;
       this.events.publish("user:created",key)
      }
    });
    modal.present();
  }

  /**
   * 点击查看券跳转到服务券页面
   * @param i 点击的订单的订单号
   */
  seeTicket(i) {
    this.stc.removeItem("back");
    console.log(i);
    let params = {
      shop_logo: i.shop_logo,
      shop_name: i.shop_name,
      order_sn: i.order_sn
    }
    let modal = this.modalCtrl.create("TicketPage", { "tic": params, "par": 0 });
    modal.onDidDismiss(data => {
    });
    modal.present();
  }

  //跳转其他页面后数据初始化更新
  again(){
    this.pop =1;
    this.bottom1 = false;
    this.orderlist=[];
    $(".contain ion-infinite-scroll-content").css("display","block");
    this.getMyOrderListAPI('')
  }
 
}
